package com.ht.api.websocket;

import java.io.EOFException;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@ServerEndpoint("/websocket/{loginId}")
@Profile("prod")
public class WebSocket {
	// 登陆用户ID
	private String loginId;

	// 所有登陆用户的session连接池
	private static ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();

	@OnOpen
	public void onOpen(Session session, @PathParam("loginId") String loginId) {
		try {
			// 写入sessionPool
			this.loginId = loginId;
			sessionPool.put(loginId, session);
			log.info("[WebSocket]建立连接成功，loginId：{}", loginId);
		} catch (Exception e) {
			log.error("[websocket]建立连接时发生异常，loginId:{}，异常消息：{}", loginId, e.getMessage(), e);
		}
	}

	@OnClose
	public void onClose() {
		try {
			sessionPool.remove(this.loginId);
			log.info("[WebSocket]断开连接，loginId：{}", loginId);
		} catch (Exception e) {
			log.error("[websocket]断开连接时发生异常，loginId：{}，异常消息：{}", loginId, e.getMessage(), e);
		}
	}

	@OnMessage
	public void onMessage(String message) {
		log.info("[websocket]收到客户端消息:{}", message);
	}

	@OnError
	public void onError(Session session, Throwable error) {
	    if (error instanceof EOFException) {
	        log.warn("[websocket]客户端意外断开连接: {}", session.getId());
	    } else {
	        log.error("[websocket]用户错误,原因:{}", error.getMessage(), error);
	    }
	}
	
	/**
	 * 给多人发送消息
	 * @param loginIdArr 登陆用户ID
	 * @param message 消息json
	 */
	public void sendMessage(String message, String... loginIdArr) {
		if (loginIdArr != null && loginIdArr.length > 0) {
			for (String loginId : loginIdArr) {
				sendMessage(sessionPool.get(loginId), loginId, message);
			}
		}
	}

	/**
	 * 发送消息
	 * @param session
	 * @param loginId
	 * @param message
	 */
	private void sendMessage(Session session, String loginId, String message) {
		if (session != null) {
			if (session.isOpen()) {
                try {
                	session.getBasicRemote().sendText(message);
                	log.info("[websocket]发送消息成功，loginId：{}，消息：{}", loginId, message);
				} catch (Exception e) {
					log.error("[websocket]发送消息有异常，loginId：{}，消息：{}，异常：{}", loginId, message, e.getMessage(), e);
				}
			} else {
				log.warn("[websocket]发送消息失败，session已关闭，loginId：{}，消息：{}", loginId, message);
			}
		} else {
			log.warn("[websocket]发送消息失败，session=null，loginId：{}，消息：{}", loginId, message);
		}
	}

}